import './style.css';
import PieChart from './components/PieChart/PieChart.js';
import InfoBarList from './components/InfoBarList/InfoBarList.js';
import WeatherBox from './components/WeatherBox/WeatherBox.js';
import TimeLine from './components/TimeLine/TimeLine.js';
import Legend from './components/Legend/Legend.js';
import Popup from './components/Popup/Popup.js';
import MapCtrl from './components/control/MapCtrl.js';
import IncidentHandler from "./components/control/IncidentHandler";
import WarnHandler from "./components/control/WarnHandler";
import RoadWeatherHandler from "./components/control/RoadWeatherHandler";
import AlarmInfoHandler from "./components/control/AlarmInfoHandler";

let pid = -1;
let backgroundId = 'e9424af07d8242adb4fa49abe40544b4';
let topId = 'b53be0ed139a459599fe9368c2304623';
let popup = null;
let map = null;
let popupBox = null;
let isBoxShow = true;
let incidentHandler = null;
let warnHandler = null;
let roadWeatherHandler = null;
let alarmInfoHandler = null;
let congestionChart = null;

const showStatus = {
    warn : false,
    incident : false,
    key : 'road'  //winds vism  tem pre warn
};

$(document).ready(function () {
    map = MapCtrl.initMap();
    // noinspection JSAnnotator
    popup = new minemap.Popup({
        offset: [0, -5]
    }).addTo(map);

    popupBox = new Popup(popup, map);
    incidentHandler = new IncidentHandler();
    warnHandler = new WarnHandler();
    roadWeatherHandler = new RoadWeatherHandler(map);
    alarmInfoHandler = new AlarmInfoHandler();

    let imageCount = 0;
    function imageLoad() {
        if (++imageCount >= 4) {
            onMapLoadAction();
        }
    }

    map.on('load',function () {
        map.loadImage('../img/1.png', function(error, image) {
            if (error) throw error;
            map.addImage('1', image);
            imageLoad();
        });
        map.loadImage('../img/2.png', function(error, image) {
            if (error) throw error;
            map.addImage('2', image);
            imageLoad();
        });
        map.loadImage('../img/3.png', function(error, image) {
            if (error) throw error;
            map.addImage('3', image);
            imageLoad();
        });
        map.loadImage('../img/4.png', function(error, image) {
            if (error) throw error;
            map.addImage('4', image);
            imageLoad();
        });
    });
    map.on('style.load', function () {
        onMapStyleLoadAction()
    });
    map.on('click',function (e) {
        onMapClickAction(e)
    });
    map.on('mousemove',function (e) {
        onMapMouseMoveAction(e)
    });
    map.on('moveend',function (e) {
        onMapMouseMoveendAction(e)
    });

    initButtonAction();
    initBoxControlButton();
    initMapTypeAction();

    initSignIn();
});

function onMapMouseMoveendAction(e) {
    const center = map.getCenter();
    minemap.util.getJSON('//minedata.cn/service/search/adminByPoint?token=a3622f2702c34957a160242d2eb0e508&location=' + center.lng + ',' + center.lat, function (error, data) {
        roadWeatherHandler.loadData(true, data);
        alarmInfoHandler.loadData(true, data);
    });
}

function onMapStyleLoadAction(backgroundId) {
    MapCtrl.initWeatherSource(map);
    MapCtrl.initWeatherLayers(map, topId, pid);
    closeLayer();
    if(!showStatus.incident) incidentHandler.setUnvisible(map);
    setTimeout(() => {
        switch (showStatus.key) {
            case 'road':
                $('#road-condition-button').click();
                break;
            case 'winds':
                $('#wins-button').click();
                break;
            case 'vism':
                $('#rh-button').click();
                break;
            case 'tem':
                $('#tem-button').click();
                break;
            case 'road':
                $('#pre-button').click();
                break;
            case 'warn':
                $('#warn-button').click();
                break;
            default:
                break;
        }
    }, 2000)
    // map.moveLayer('b33c20be63fc47c58d83d5b143c62034', topId);
    // roadConditionButton.className = 'weather-switch-selected';
}

function onMapLoadAction() {
    document.getElementsByClassName('minemap-ctrl')[0].parentElement.innerHTML = '';

    $('#loading').css('display','none');

    incidentHandler.loadData(map, true);  //交通事件统计
    congestionChart = new InfoBarList('congestion-chart', obj1); 

    const center = map.getCenter();
    minemap.util.getJSON('//minedata.cn/service/search/adminByPoint?token=a3622f2702c34957a160242d2eb0e508&location=' + center.lng + ',' + center.lat, function (error, data) {
        roadWeatherHandler.loadData(true, data);
        alarmInfoHandler.loadData(true, data);
    });

    // map.moveLayer('b519feeafff3466091df41876924bf21', topId);
    // map.moveLayer('563da56af516487aa272c0bcc914815a', topId);
    // map.moveLayer('a459eaf51c9a4bdf85645de25a929420', topId);
    // map.moveLayer('d7bb38190113411486f0dc41601f926a', topId);

    document.getElementById('loading').style.display = 'none';
}

function onMapClickAction(e) {

    let layerIds = [];
    if (showStatus.incident && map.getLayer('5a3ea454892d4824b622cdabb48950a2')) {
        layerIds.push('5a3ea454892d4824b622cdabb48950a2');
    }
    if (showStatus.incident && map.getLayer('3423d2a936064f0b90561229a5cd8aba')) {
        layerIds.push('3423d2a936064f0b90561229a5cd8aba');
    }
    layerIds.push('warn')
    // if (map.getLayer('road-speed-symbol')) {
    //     layerIds.push('road-speed-symbol');
    // }
    let features = map.queryRenderedFeatures(e.point, {layers: layerIds});
    let style = map.getCanvas().style;
    if (features && features.length > 0) {
        style.cursor = 'pointer'; //光标
    } else {
        style.cursor = '';
    }

    if (features && features.length > 0) {
        const f = features[0];

        if ((f.layer.id == '5a3ea454892d4824b622cdabb48950a2' || f.layer.id == '3423d2a936064f0b90561229a5cd8aba')  && showStatus.incident) {
            incidentHandler.onMouseClickHandler(map, f,e);
        } else {
            incidentHandler.onMouseClickHandler(map, null,e);
        }
        if (f.layer.id == 'warn') {
            warnHandler.onMouseClickWarnHandler(map, f,e);
        } else {
            warnHandler.onMouseClickWarnHandler(map, null,e);
        }
    }
}
function onMapMouseMoveAction(e) {
    let feature = null;
    let layerIds = [];
    if (showStatus.incident && map.getLayer('5a3ea454892d4824b622cdabb48950a2')) {
        layerIds.push('5a3ea454892d4824b622cdabb48950a2');
    }
    if (showStatus.incident && map.getLayer('3423d2a936064f0b90561229a5cd8aba')) {
        layerIds.push('3423d2a936064f0b90561229a5cd8aba');
    }
    // if (map.getLayer('road-speed-symbol')) {
    //     layerIds.push('road-speed-symbol');
    // }
    const features = map.queryRenderedFeatures(e.point, {layers: layerIds});
    if (features && features.length > 0) {
        feature = features[0];
    }
    let style = map.getCanvas().style;
    if (feature) {
        style.cursor = 'pointer';
        if ((feature.layer.id == '5a3ea454892d4824b622cdabb48950a2' || feature.layer.id == '3423d2a936064f0b90561229a5cd8aba') && showStatus.incident) {
            incidentHandler.onMouseMoveHandler(map, feature);  //incidentHandler
        } else {
            incidentHandler.onMouseMoveHandler(map, null);
        }
    } else {
        style.cursor = '';
        incidentHandler.onMouseMoveHandler(map, null);
    }
}

const obj1 = {
    "color1": "#FF5500",
    "color2": "#EDCF6D",
    "array": [{
        "name": '广粤支路',
        "sub": '从汶水东路至粤秀路',
        "value": 23.5
    },
        {
            "name": '广粤支路',
            "sub": '从粤秀路至汶水东路',
            "value": 20.3
        },
        {
            "name": '何家湾路',
            "sub": '从国权北路至长江南路',
            "value": 19.4
        },
        {
            "name": '金汇路',
            "sub": '从程家桥路至吴中路',
            "value": 19.2
        },
        {
            "name": '新开河路',
            "sub": '从人民路至中山东二路',
            "value": 18.3
        },
        {
            "name": '东江阴街',
            "sub": '从跨龙路至柳市路',
            "value": 18.0
        },
        {
            "name": '新沪路',
            "sub": '从华灵路至沪太路',
            "value": 18.0
        },
        {
            "name": '柳市路',
            "sub": '从东江阴街至陆家浜路',
            "value": 18.0
        },
        {
            "name": '空港六路',
            "sub": '从沪青平公路至迎宾三路',
            "value": 17.7
        },
        {
            "name": '百色路',
            "sub": '从龙吴路至老沪闵路',
            "value": 16.8
        },
    ]
};

const legendObjRoad = {
    name: '实时路况',
    arrName: ['严重拥堵', '拥堵', '缓行', '畅通'],
    // arrColor: ['#A189FF', '#FE4B3C', '#F8CA37', '#28AD86']
    arrColor: ['#AD1717', '#E53434', '#FF9901', '#66CC01']
}

const legendObjTem = {
    name: '图例',
    arrName: ['>-5', '-5~-15', '-15~-30', '<-30'],
    arrColor: ['#28AD86', '#F8CA37', '#FE4B3C', '#A189FF']
    // arrColor: ['rgb(230, 245, 190)', 'rgb(254, 224, 139)', 'rgb(244, 108, 67)', 'rgb(213, 62, 80)']
}

const legendObjWins = {
    name: '图例',
    arrName: ['<10.8', '10.8-20.8', '20.8-28.5', '>28.5'],
    arrColor: ['#28AD86', '#F8CA37', '#FE4B3C', '#A189FF']
    // arrColor: ['rgba(255, 255, 255, 0.05)', 'gba(255, 255, 255, 0.3)', 'rgba(255, 255, 255, 0.5)', 'rgba(255, 255, 255, 0.7)']
}

const legendObjPre = {
    name: '图例',
    arrName: ['0-2.0', '2.0-4.0', '4.0-8.0', '>8.0'],
    arrColor: ['#28AD86', '#F8CA37', '#FE4B3C', '#A189FF']
    // arrColor: ['#C7F5FF', '#5BFDF8', '#0B98E3', '#0049C2']
}

const lengthObjRh = {
    name: '图例',
    arrName: ['>10', '1-10', '0.5-1', '<0.5'],
    arrColor: ['#28AD86', '#F8CA37', '#FE4B3C', '#A189FF']
    // arrColor: ['rgba(160, 160, 160, 0.05)', 'rgba(160, 160, 160, 0.3)', 'rgba(160, 160, 160, 0.5)', 'rgba(160, 160, 160, 0.7)']
}

let roadWeatherChart = null;
let weatherChart = null;
// const timeLine = new TimeLine('timeline-box', 16, (num) => {});
// timeLine.disappear();
const legend = new Legend('legend', legendObjRoad);

let roadConditionButton = null;
let temButton = null;
let winsButton = null;
let rhButton = null;
let preButton = null;
let incidentButton = null;
let warnButton = null;
let odButton = null;

let mapTypeStyle1 = null;
let mapTypeStyle2 = null;

// 地图切换
function initMapTypeAction() {
    mapTypeStyle1 = document.getElementsByClassName("mapTypeCard earth")[0];
    mapTypeStyle2 = document.getElementsByClassName("mapTypeCard normal")[0];

    mapTypeStyle1.addEventListener('click', ()=> {
       if (map.solution == 3756) {
           toggle(4389);
           backgroundId = '227c6407ccc246929af0270614eb4f16';
           topId = '9f458ee0d170450e98092d206dd616ab';
           // noinspection JSAnnotator
           // backgroundId = '227c6407ccc246929af0270614eb4f16';
       }
    });
    mapTypeStyle2.addEventListener('click', ()=> {
        if (map.solution == 4389) {
            toggle(3756);
            backgroundId = 'e9424af07d8242adb4fa49abe40544b4';
            topId = 'b53be0ed139a459599fe9368c2304623';
            // noinspection JSAnnotator
            // backgroundId = 'e9424af07d8242adb4fa49abe40544b4';
        }
    });
    function toggle(id) {
        //if (map.isStyleLoaded())
        map.accessToken = 'a3622f2702c34957a160242d2eb0e508';
        map.solution = id;
        map.setStyle('//minedata.cn/service/solu/style/id/'+id);
    }
}

function initButtonAction() {
        initRoadConditionButtonAction();
        initIncidentButtonAction();
        initTemButtonAction();
        initRhButtonAction();
        initWinsButtonAction();
        initPreButtonAction();
        // initOdButtonAction();
        initWarnButtonAction();
}

function initRoadConditionButtonAction() {
    roadConditionButton = document.getElementById('road-condition-button');
    roadConditionButton.addEventListener('click', () => {
        closeLayer();
        // map.moveLayer('b519feeafff3466091df41876924bf21', topId);
        // map.moveLayer('563da56af516487aa272c0bcc914815a', topId);
        // map.moveLayer('a459eaf51c9a4bdf85645de25a929420', topId);
        // map.moveLayer('d7bb38190113411486f0dc41601f926a', topId);
        // if (map.solution == 3756) {
        //     map.moveLayer('b33c20be63fc47c58d83d5b143c62034', topId);
        // }
        // if (map.solution == 4389) {
        //     map.moveLayer('c72ceefd8ac84b03b84ad2c07286dbc9', topId);
        // }
        if (map.solution == 3756) {
            map.moveLayer('b33c20be63fc47c58d83d5b143c62034', topId);
        }
        if (map.solution == 4389) {
            map.moveLayer('c72ceefd8ac84b03b84ad2c07286dbc9', topId);
        }

        roadConditionButton.className = 'weather-switch-selected';
        legend.setData(legendObjRoad);
        showStatus.key = 'road';
    });
}

function initIncidentButtonAction() {
    incidentButton = document.getElementById('incident-button');
    incidentButton.addEventListener('click', () => {
        showStatus.incident = !showStatus.incident;
        incidentButton.className = showStatus.incident ? 'weather-switch-selected' : 'weather-switch-not-selected';
        if (showStatus.incident) {
            incidentHandler.setVisible(map);
        }else {
            incidentHandler.setUnvisible(map)
        }
        map.flyTo({
            center: [121.47375, 31.23026],
            zoom: 10
        })
    });
}

function initTemButtonAction() {
    temButton = document.getElementById('tem-button');
    temButton.addEventListener('click', () => {
        closeLayer();
        map.moveLayer('tem1', topId);
        map.moveLayer('tem2', topId);
        map.moveLayer('tem3', topId);
        map.moveLayer('tem4', topId);
        // map.setLayoutProperty('tem', 'visibility', 'visible');
        temButton.className = 'weather-switch-selected';
        legend.setData(legendObjTem);
        showStatus.key = 'tem';
        // roadWeatherChart = new InfoBarList('road-weather-chart', temInfoObj);
    });
}

function initRhButtonAction() {
    rhButton = document.getElementById('rh-button');
    rhButton.addEventListener('click', () => {
        closeLayer();
        map.moveLayer('vism1', topId);
        map.moveLayer('vism2', topId);
        map.moveLayer('vism3', topId);
        map.moveLayer('vism4', topId);
        // map.setLayoutProperty('vism', 'visibility', 'visible');
        rhButton.className = 'weather-switch-selected';
        legend.setData(lengthObjRh);
        showStatus.key = 'vism';
        // roadWeatherChart = new InfoBarList('road-weather-chart', rhInfoObj);
        // closeLayer();
        // map.moveLayer('vism', topId);
        // rhButton.className = 'weather-switch-selected';
        // legend.setData(lengthObjRh);
        // roadWeatherChart = new InfoBarList('road-weather-chart', rhInfoObj);
    });
}

function initWinsButtonAction() {
    winsButton = document.getElementById('wins-button');
    winsButton.addEventListener('click', () => {
        closeLayer();
        map.moveLayer('winds1', topId);
        map.moveLayer('winds2', topId);
        map.moveLayer('winds3', topId);
        map.moveLayer('winds4', topId);
        // map.setLayoutProperty('winds', 'visibility', 'visible');
        winsButton.className = 'weather-switch-selected';
        legend.setData(legendObjWins);
        showStatus.key = 'winds';
        // roadWeatherChart = new InfoBarList('road-weather-chart', winsInfoObj);
    });
}

function initPreButtonAction() {
    preButton = document.getElementById('pre-button');
    preButton.addEventListener('click', () => {
        closeLayer();
        map.moveLayer('pre1', topId);
        map.moveLayer('pre2', topId);
        map.moveLayer('pre3', topId);
        map.moveLayer('pre4', topId);
        // map.setLayoutProperty('pre', 'visibility', 'visible');
        preButton.className = 'weather-switch-selected';
        // timeLine.show();
        legend.setData(legendObjPre)
        showStatus.key = 'pre';
        // roadWeatherChart = new InfoBarList('road-weather-chart', preInfoObj);
    });
}

function initOdButtonAction() {
    odButton = document.getElementById('od-button');
    odButton.addEventListener('click', ()=> {

    })
}

function initWarnButtonAction() {
    warnButton = document.getElementById('warn-button');
    warnButton.addEventListener('click', ()=> {
        showStatus.warn = !showStatus.warn;
        warnButton.className = showStatus.warn ? 'weather-switch-selected' : 'weather-switch-not-selected';
        if (showStatus.warn) {
            warnHandler.setVisible(map)
        }else {
            warnHandler.setUnvisible(map)
        }
        // closeLayer();
        // // map.moveLayer('warn', topId);
        // map.setLayoutProperty('warn', 'visibility', 'visible');
        // warnButton.className = 'weather-switch-selected';
        // showStatus.key = 'warn';
        // // WarnHandler.roadHandler();
    });
}

// function initIncidentButtonAction() {
//     incidentButton = document.getElementById('incident-button');
//     incidentButton.addEventListener('click', () => {
//         showStatus.incident = !showStatus.incident;
//         incidentButton.className = showStatus.incident ? 'weather-switch-selected' : 'weather-switch-not-selected';
//         if (showStatus.incident) {
//             incidentHandler.setVisible(map);
//         }else {
//             incidentHandler.setUnvisible(map)
//         }
//         map.flyTo({
//             center: [121.47375, 31.23026],
//             zoom: 10
//         })
//     });
// }


function initBoxControlButton() {
    const button = document.getElementById('box-control');
    button.addEventListener('click', (e) => {
        if (isBoxShow) {
            $('#incident-info').animate({
                left: '-440px'
            });
            $('#congestion-info').animate({
                left: '-440px'
            });
            $('#weather-info').animate({
                right: '-440px'
            });
            $('#alarm-info').animate({
                right: '-440px'
            });
            $('.weather-switch').animate({
                left: '50px'
            });
            $('#legend').animate({
                left: '50px'
            });
            $('#mapType-wrapper').animate({
                right: '50px'
            });
            isBoxShow = false;
            console.log(e.target)
            document.getElementById('box-control-button-text').innerHTML = '显示窗口';
        } else {
            $('#incident-info').animate({
                left: '50px'
            });
            $('#congestion-info').animate({
                left: '50px'
            });
            $('#weather-info').animate({
                right: '50px'
            });
            $('#alarm-info').animate({
                right: '50px'
            });
            $('.weather-switch').animate({
                left: '510px'
            });
            $('#legend').animate({
                left: '510px'
            });
            $('#mapType-wrapper').animate({
                right: '510px'
            });
            isBoxShow = true;
            document.getElementById('box-control-button-text').innerHTML = '隐藏窗口';
        }
    });
}


function closeLayer() {
    if (map.solution == 3756) {
        map.moveLayer('b33c20be63fc47c58d83d5b143c62034', backgroundId);
    }
    if (map.solution == 4389) {
        map.moveLayer('c72ceefd8ac84b03b84ad2c07286dbc9', backgroundId);
    }
    roadConditionButton.className = 'weather-switch-not-selected';
    preButton.className = 'weather-switch-not-selected';
    temButton.className = 'weather-switch-not-selected';
    winsButton.className = 'weather-switch-not-selected';
    rhButton.className = 'weather-switch-not-selected';
    // odButton.className = 'weather-switch-not-selected';
    // warnButton.className = 'weather-switch-not-selected';

    // map.setLayoutProperty('pre', 'visibility', 'none');
    map.moveLayer('pre1', backgroundId);
    map.moveLayer('pre2', backgroundId);
    map.moveLayer('pre3', backgroundId);
    map.moveLayer('pre4', backgroundId);
    // map.setLayoutProperty('tem', 'visibility', 'none');
    map.moveLayer('tem1', backgroundId);
    map.moveLayer('tem2', backgroundId);
    map.moveLayer('tem3', backgroundId);
    map.moveLayer('tem4', backgroundId);
    // map.setLayoutProperty('winds', 'visibility', 'none');
    map.moveLayer('winds1', backgroundId);
    map.moveLayer('winds2', backgroundId);
    map.moveLayer('winds3', backgroundId);
    map.moveLayer('winds4', backgroundId);
    // map.setLayoutProperty('vism', 'visibility', 'none');
    map.moveLayer('vism1', backgroundId);
    map.moveLayer('vism2', backgroundId);
    map.moveLayer('vism3', backgroundId);
    map.moveLayer('vism4', backgroundId);
    // map.setLayerProperty('od', 'visibility', 'none')
    // map.moveLayer('od', backgroundId);

    // map.setLayoutProperty('warn', 'visibility', 'none');
    // map.moveLayer('warn', backgroundId);
}

// 初始化登录框
function initSignIn() {
    $('#sign-in').click((e) => {
        $('#sign-in-mask').css('display', 'block');
    });
    $('#sign-in-submit').click((e) => {
        e.preventDefault();
        if ($("#form-email").val() == 'admin' &&
            $("#form-password").val() == 'admin') {
            $('#sign-in-mask').css('display', 'none');
            $('#sign-up').css('display', 'none');
            $('#sign-in').css('display', 'none');
            $('#user-info').css('display', 'block');
        } else {
            alert('账号密码错误！');
        }
    });
    $('#sign-up-submit').click((e) => {
        e.preventDefault();
    });
    $('#sign-in-close-button').click((e) => {
        e.preventDefault();
        $('#sign-in-mask').css('display', 'none');
    });
}